class User < ApplicationRecord
  authenticates_with_sorcery!

  # 在用户上访问到这两个属性，需要下面的手动声明
  attr_accessor :password, :password_confirmation

  #设置要验证的字段
  validates_presence_of :email, message: "邮箱不能为空"
  #验证唯一
  validates :email, uniqueness: true

  # 当是新记录，或者修改时，验证密码和确认密码，
  validates_presence_of :password, message: "密码不能为空",
                        if: :need_validate_password
  validates_presence_of :password_confirmation, message: "密码确认不能为空",
                        if: :need_validate_password
  validates_confirmation_of :password, message: "密码不一致",
                            if: :need_validate_password
  validates_length_of :password, message: "密码最短为6位", minimum: 6,
                      if: :need_validate_password

  private
  def need_validate_password
    self.new_record? ||
      (!self.password.nil? || !self.password_confirmation.nil?)
  end
end
